//
//  ASTableCell.swift
//  flow
//
//  Created by tong on 2017/7/16.
//  Copyright © 2017年 tong. All rights reserved.
//

import UIKit
import AsyncDisplayKit
import Eelay
//extension ASDisplayNode{
//    private struct __AssociatedKeys {
//        static var notify_key = "__easy_notify_key"
//    }
//
//    public var __notice: EasyNotification {
//        get {
//            if let obj = objc_getAssociatedObject(self, &__AssociatedKeys.notify_key) as? EasyNotification
//            {
//                return obj
//            }
//            let obj = EasyNotification()
//            self.__notice = obj
//            return obj
//
//        }
//        set {
//            objc_setAssociatedObject(self, &__AssociatedKeys.notify_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//        }
//    }
//}



extension JoCellNode{
    
    public var opened:Bool{
        get{
            return mo.model["__opened__","0"] == "1"
        }
        set{
            if newValue{
                mo.model["__opened__"] = "1"
            }else{
                mo.model["__opened__"] = "0"
            }
        }
    }
    
    public weak var __collectionNode:ASCollectionNode?{
        get{
            return (self.delegate as? ASColListController)?.collectionNode
        }
    }
    
    public weak var __tableNode:ASTableNode?{
        get{
            
            return (self.delegate as? ASListController)?.tableNode
        }
    }
    
    public var __indexPath:IndexPath{
        get{
            let section  = mo.model[int:"__section__",0]

            if let tab = __tableNode{
                let list = DataNode.path(node: "section\(section)", tab.model, value: NSMutableArray())
                let row = list.index(of: mo.model)
                return IndexPath(row: row, section: section)
            }
            if let col = __collectionNode
            {
                let list = DataNode.path(node: "section\(section)", col.model, value: NSMutableArray())
                let row = list.index(of: mo.model)

                return IndexPath(item: row, section: section)
            }
            return IndexPath(row: 0, section: 0)
        }
    }
    
    
  
}

public class MoSeparator:MoBaseNode{
    lazy var line = ASDisplayNode()
    public var inset:UIEdgeInsets = .zero
    let seperatorHeight:CGFloat = TP.separatorHeight
    public override func initStyle() {
        backgroundColor = .clear
        
    }
    
    public override func specGetter() -> _Spec {
        return .inset([], UIEdgeInsets(top: 0, left: inset.left, bottom: 0, right: inset.right), child: line["\(seperatorHeight)"])
    }
    
}
open class  JoCellNode:ASCellNode,MoAtrributeProtocol,MoUITraitEnvironment
{
    
    open func mo_change_localizable(obj: Any?) {
        
    }
    
    open func mo_set_controller(controller: UIViewController) {
        
    }
    
    open func mo_model_willSet(new: NSMutableDictionary) {
        
    }
    
    open func mo_model_reload() {
        
    }
    
    open func mo_model_relase(current: NSMutableDictionary) {
        
    }
    
    
    open func didSelect(at indexPath:IndexPath) {
    
    }
    
    open func mo_detail_willSet(new: NSMutableDictionary) {
        
    }
    
    open func mo_detail_reload() {
        
    }
    
    open func mo_detail_relase(current: NSMutableDictionary) {
        
    }
    
    open func mo_will_display() {
        
    }
    
    
    open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    }
    
  
    open var mo:MoAtrribute{
        get{
            if let _mo = __extention["MoAtrributeInstance"] as? MoAtrribute{
                _mo.ower = self
                return _mo
                
            }
            let _mo = MoAtrribute()
            __extention["MoAtrributeInstance"] = _mo
            _mo.ower = self
            return _mo
        }
        set{
            newValue.ower = self
            __extention["MoAtrributeInstance"] = newValue
            self.mo_model_willSet(new: newValue.model)
            self.mo_detail_willSet(new: newValue.detail)
            self.mo_model_reload()
        }
    }

    public var __topline = ASDisplayNode()

    public var __line = MoSeparator()
    
    public var __touchBt = ASButtonNode()
        
    public var separatorTopHeight: CGFloat = 0
    public var separatorTopColor: UIColor = UIColor.separator_color
    
    public var separatorHeight: CGFloat = 0
    public var separatorColor: UIColor = UIColor.separator_color{
        didSet{
            __line.line.view.backgroundColor = separatorColor
        }
    }


    
    
    public var layoutSpec = ASLayoutSpec()
    public weak var delegate:JoTableCellDelegate?
    public weak var content_controller:UIViewController?{
        get{
            
            return self.delegate as? UIViewController
        }
    }
    
    
    open func specGetter()->_Spec{
        return .stack([], childs: [])
    }
    
    public var internalCellTouch = false
    
    @objc open func cellTouch(){
    }
    
    open func indexPathDelete() {
        
        if let colNode = __collectionNode
        {
            let path = __indexPath
            let list = DataNode.path(node: "section\(path.section)", colNode.model, value: NSMutableArray())
            _ = list.index(of: mo.model)
            list.remove(mo.model)
            colNode.deleteItems(at: [path])
            if list.count < 1{
                if let ctr = self.content_controller as? ASColPaginatorController
                {
                    if let leb = (self.content_controller as? ASColPaginatorController)?.backMsgView as? UILabel
                    {
                        leb.text = ctr.paginator.empty_msg
                    }
                }
                
            }
        }
        if let tableNode = __tableNode
        {
            let path = __indexPath
            let list = DataNode.path(node: "section\(path.section)", tableNode.model, value: NSMutableArray())
            _ = list.index(of: mo.model)
            list.remove(mo.model)
            tableNode.deleteRows(at: [path], with: .fade)
            if list.count < 1{
                if let ctr = self.content_controller as? ASPaginatorController
                {
                    if let leb = (self.content_controller as? ASPaginatorController)?.backMsgView as? UILabel
                    {
                        leb.text = ctr.paginator.empty_msg
                    }
                }
                
            }
        }
       
    }
    
    open func indexPathUpdate(animation:UITableView.RowAnimation = .none) {
        if let colNode = __collectionNode
        {
            colNode.reloadItems(at: [__indexPath])
        }
        else{
            __tableNode?.reloadRows(at: [__indexPath], with: animation)
        }
    }
    
    public var __constrainedSize:ASSizeRange = ASSizeRange(min: CGSize(width: Swidth, height: 0.0), max: CGSize(width: Swidth, height: 1000000))
    override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
        self.__constrainedSize = constrainedSize
        
        let lay = fastLayoutSpec(_spec: specGetter())
        
        let haveSpec = (separatorTopHeight > 0) || (separatorHeight > 0)
        
        if haveSpec
        {
//            let insetSpec = ASInsetLayoutSpec(insets: self.separatorInset, child: __line)
            var childs = [ASLayoutElement]()
            if separatorTopHeight > 0
            {
                __topline.backgroundColor = separatorTopColor
                __topline.style.height = ASDimension(unit: .points, value: separatorTopHeight)
                __topline.style.flexShrink = 1
                childs.append(__topline)
            }
            childs.append(lay)
            if separatorHeight > 0
            {
                
                __line.style.height = ASDimension(unit: .points, value: separatorHeight)
                __line.style.flexShrink = 1
                childs.append(__line)
            }

            let spec = ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .spaceBetween, alignItems: .stretch, children: childs)
            
            if !internalCellTouch
            {
                return spec
            }
            else{
                return ASBackgroundLayoutSpec(child: spec, background: __touchBt)
//                return  ASOverlayLayoutSpec(child: spec, overlay: __touchBt)
            }
        }
        if internalCellTouch{
            return ASBackgroundLayoutSpec(child: lay, background: __touchBt)
//            return  ASOverlayLayoutSpec(child: lay, overlay: __touchBt)
        }
        return lay
    }
    
 
    open func active(ID actionID:String,object:NSMutableDictionary? = nil) {
        if let obj = object
        {
            self.delegate?.touch(cell: self, actionID: actionID, model: obj)
        }
        else
        {
            self.delegate?.touch(cell: self, actionID: actionID, model: mo.model)
        }
    }
    
    
    open func addLayoutRules()
    {
        //        self.fillPropertyViews()
    }
    
    
    open func willLayoutRules()
    {
        //        self.fillPropertyViews()
    }
    
    open func didLayoutRules()
    {
        //        self.fillPropertyViews()
    }
    
    public override init() {
        super.init()
  
        __notice.observer(TP.Notice.traitCollectionDidChange,TP.Notice.localizableDidChange) {[weak self] (t, ntype) in
            switch ntype.name.rawValue{
            case TP.Notice.traitCollectionDidChange.name.rawValue:
                self?.traitCollectionDidChange(nil)
            case TP.Notice.localizableDidChange.name.rawValue:
                if let n = self{
                    n.mo_change_localizable(obj: nil)
                }
            default:
                break
            }
        }

        self.automaticallyManagesSubnodes = true
        __touchBt.addTarget(self, action: #selector(cellTouch), forControlEvents: .touchUpInside)
//        __touchBt.backgroundColor = .red
        selectionStyle = .none
//        addSubnode(__line)
        willLayoutRules()
        addLayoutRules()
        didLayoutRules()
    }
    
    
    deinit {
    }
}
//
//extension JoCellNode{
//    open var collectionNode:ASCollectionNode?{
//          get{
//              if let ctr = mo.controller as? ASColListController{
//                  return ctr.collectionNode
//              }
//              return nil
//          }
//      }
//
//      open var tableNode:ASTableNode?{
//          get{
//              if let ctr = mo.controller as? ASListController{
//                  return ctr.tableNode
//              }
//              return nil
//          }
//      }
//
//
//      open func mo_update_height(){
//          let row = mo.model[int:"__row__",0]
//          let section = mo.model[int:"__section__",0]
//          if let tn = tableNode{
//              tableNode?.reloadRows(at: [IndexPath(row: row, section: section)], with: .fade)
//              return
//          }
//          if let cn = collectionNode{
//              collectionNode?.reloadItems(at: [IndexPath(item: row, section: section)])
//          }
//      }
//
//}

//
//protocol NodeModelData {
//    var model:NSMutableDictionary{get set}
//    func loadModelContent()
//    func willReleaseModel(old oldModdel:NSMutableDictionary)
//    func willLoad(model:NSMutableDictionary)
//}
//
//extension ASCellNode:NodeModelData
//{
//    private struct AssociatedKeys {
//        static var model = "node_model_key"
//        static var style = "node_style_key"
//    }
//
//    open func willLoad(model:NSMutableDictionary){}
//
//    open func loadModelContent() {}
//
//    open func willReleaseModel(old oldModdel:NSMutableDictionary) {}
//
//    public var model: NSMutableDictionary {
//        get {
//            if let obj = objc_getAssociatedObject(self, &AssociatedKeys.model) as? NSMutableDictionary
//            {
//                return obj
//            }
//            let obj = NSMutableDictionary()
//            self.model = obj
//            return obj
//
//        }
//        set {
//            self.willLoad(model: newValue)
//            if let obj = objc_getAssociatedObject(self, &AssociatedKeys.model) as? NSMutableDictionary
//            {
//                self.willReleaseModel(old:obj)
//            }
//
//            objc_setAssociatedObject(self, &AssociatedKeys.model, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//            self.loadModelContent()
//        }
//    }
//
//    public var __style: NSMutableDictionary {
//        get {
//            if let obj = objc_getAssociatedObject(self, &AssociatedKeys.style) as? NSMutableDictionary
//            {
//                return obj
//            }
//
//            let obj = NSMutableDictionary()
//            self.__style = obj
//            return obj
//
//        }
//        set {
//            objc_setAssociatedObject(self, &AssociatedKeys.style, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//            self.loadModelContent()
//        }
//    }
//}
//
//
//
//

